package view.publics;

import java.awt.Color;
import java.awt.Component;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import main.ServicesList;
import model.publics.Supplier;
import model.system.Policy;
import model.system.SystemMenu;
import utility.Constants;
import utility.NameValueList;
import utility.com.ColumnResizer;
import view.RekapTemplate;


public class SupplierListFrm extends RekapTemplate {

    private SupplierTM tableModel;
    private List<Supplier> suppliers;
    private Object oldValue, newValue;
    private ItemListener comboboxListener = new ComboboxListener();
    
    public SupplierListFrm() {
        initComponents();       
        txtKodeFilter.addKeyListener(new ActionKeyListener());
        txtNamaFilter.addKeyListener(new ActionKeyListener());
        txtKodeFilter.addFocusListener(new ActionFocusGained());
        txtNamaFilter.addFocusListener(new ActionFocusGained());
    }
    
    @Override
    public void execute(boolean withVisible, int id) {
        initGrid();  
        Policy policy = ServicesList.getSystemGroupAccessService().allowAccess(SystemMenu.MENU_PURCHASE_SUPPLIER, ServicesList.getSystemUserService().getActiveUser().getSystemGroup().getGroupId());
        
        btnAdd.setVisible(policy.isCanAdd());
        btnDelete.setVisible(policy.isCanDelete());
        btnEdit.setVisible(policy.isCanEdit());
        btnPrint.setVisible(policy.isCanPrint());
        if (withVisible) { setVisible(true); }
    }
    
    @Override
    public void initGrid(){
        tableModel = new SupplierTM();
        grid.setModel(tableModel);
        
        
    }
    
    @Override
    public void initFilter(){
        cmbDays.removeItemListener(comboboxListener);
        txtKodeFilter.setText("");
        txtNamaFilter.setText("");
        cmbDays.setSelectedIndex(0);
        cmbDays.addItemListener(comboboxListener);
    }
    
    public Map<NameValueList, Object> getFilter(){
        Map<NameValueList, Object> params = new HashMap<>();
        if(!"".equals(txtNamaFilter.getText())) {
            params.put(new NameValueList("nama", Constants.OPERATOR_LIKE), "%"+txtNamaFilter.getText()+"%"); }

        if(!"".equals(txtKodeFilter.getText())) { 
            params.put(new NameValueList("kode", Constants.OPERATOR_EQUAL), txtNamaFilter.getText()); }
         
        if (cmbDays.getSelectedIndex() > 0) {
             params.put(new NameValueList("(substring(suprincipal.jadwal,"+cmbDays.getSelectedIndex()+",1))", Constants.OPERATOR_EQUAL), "1"); }
        
        params.put(new NameValueList(null, Constants.OPERATOR_ORDERBY), "nama"); 
        return params;
    }
    
    @Override
    public void loadData() {
        tableModel.clear();
        suppliers = ServicesList.getSupplierService().getAll(0, 1000, getFilter());
        tableModel.add(suppliers);
        DefaultTableCellRenderer rightCellRender = new DefaultTableCellRenderer();
        rightCellRender.setHorizontalAlignment(SwingConstants.RIGHT);
        grid.getColumnModel().getColumn(0).setCellRenderer(rightCellRender);
        grid.getColumnModel().getColumn(0).setMaxWidth(60);
        ColumnResizer.adjustColumnPreferredWidths(grid);
        
        //look style
        final TableCellRenderer header = grid.getTableHeader().getDefaultRenderer();
        grid.getTableHeader().setDefaultRenderer(new TableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                JLabel lbl = (JLabel) header.getTableCellRendererComponent(table, 
                      value, isSelected, hasFocus, row, column);
                lbl.setBorder(BorderFactory.createEmptyBorder(5,1,5,1));   

                switch (column) {
                    case 0: lbl.setHorizontalAlignment(SwingConstants.RIGHT); break;
                    default: lbl.setHorizontalAlignment(SwingConstants.LEFT); break;   
                }
                lbl.setForeground(Color.WHITE);
                lbl.setBackground(Color.DARK_GRAY);
                return lbl;
            }
        });
        grid.setGridColor(Color.LIGHT_GRAY);
    }
    
    @Override
    public void updateGrid() {
        int row = grid.getSelectedRow();
        if (row > -1) {
            if(suppliers.get(row) != null) {
                new SupplierFrm().execute(suppliers.get(row).getId());
                Supplier updatedData = ServicesList.getSupplierService().getSupplier(suppliers.get(row).getId());
                tableModel.set(row, updatedData);
            }
        }
    }
    
    @Override
    public void insertGrid() {
        int itemId = new SupplierFrm().execute(0);
        if (itemId>0) {
            Supplier insertedData = ServicesList.getSupplierService().getSupplier(itemId);
            tableModel.add(insertedData);
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        btnAdd = new javax.swing.JButton();
        btnEdit = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();
        btnLoad = new javax.swing.JButton();
        btnPrint = new javax.swing.JButton();
        jSplitPane2 = new javax.swing.JSplitPane();
        jPanel1 = new javax.swing.JPanel();
        txtKodeFilter = new javax.swing.JTextField();
        txtNamaFilter = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        cmbDays = new javax.swing.JComboBox();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        grid = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);
        jToolBar1.setSize(this.getWidth(), 50);

        btnAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/edit_add.png"))); // NOI18N
        btnAdd.setText("Tambah");
        btnAdd.setFocusable(false);
        btnAdd.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnAdd.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });
        jToolBar1.add(btnAdd);

        btnEdit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/edit.png"))); // NOI18N
        btnEdit.setText("Edit");
        btnEdit.setFocusable(false);
        btnEdit.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnEdit.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditActionPerformed(evt);
            }
        });
        jToolBar1.add(btnEdit);

        btnDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/edit_remove.png"))); // NOI18N
        btnDelete.setText("Hapus");
        btnDelete.setFocusable(false);
        btnDelete.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnDelete.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(btnDelete);

        btnLoad.setIcon(new javax.swing.ImageIcon(getClass().getResource("/reload.png"))); // NOI18N
        btnLoad.setText("Load");
        btnLoad.setFocusable(false);
        btnLoad.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnLoad.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnLoad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLoadActionPerformed(evt);
            }
        });
        jToolBar1.add(btnLoad);

        btnPrint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/print.png"))); // NOI18N
        btnPrint.setText("Print");
        btnPrint.setToolTipText("");
        btnPrint.setFocusable(false);
        btnPrint.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnPrint.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnPrint.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPrintActionPerformed(evt);
            }
        });
        jToolBar1.add(btnPrint);

        jSplitPane2.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        txtKodeFilter.setName("txtKodeFilter"); // NOI18N

        txtNamaFilter.setName("txtNamaFilter"); // NOI18N

        jLabel1.setText("Kode :");

        jLabel2.setText("Nama :");

        jLabel3.setText("Jadwal :");

        cmbDays.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Semua", "Senin", "Selasa", "Rabu", "Kamis", "Jum'at", "Sabtu" }));
        cmbDays.setName("cmbDays"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(txtKodeFilter, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmbDays, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 356, Short.MAX_VALUE))
                    .addComponent(txtNamaFilter))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtKodeFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel3)
                    .addComponent(cmbDays, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNamaFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jSplitPane2.setTopComponent(jPanel1);

        grid.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        grid.setName("grid"); // NOI18N
        jScrollPane2.setViewportView(grid);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 670, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 353, Short.MAX_VALUE)
        );

        jSplitPane2.setRightComponent(jPanel2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jSplitPane2)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSplitPane2))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        new SupplierFrm().execute(0);
        insertGrid();
    }//GEN-LAST:event_btnAddActionPerformed

    private void btnPrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrintActionPerformed

    }//GEN-LAST:event_btnPrintActionPerformed

    private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
        updateGrid();
    }//GEN-LAST:event_btnEditActionPerformed

    private void btnLoadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoadActionPerformed
        loadData();
    }//GEN-LAST:event_btnLoadActionPerformed

    class ActionKeyListener implements KeyListener {
        @Override public void keyTyped(KeyEvent e) {} 
        @Override public void keyReleased(KeyEvent e) {}
        
        @Override public void keyPressed(KeyEvent e) {
            switch (e.getKeyCode()) { 
                
                case KeyEvent.VK_ENTER: 
                    switch(e.getComponent().getName()) {
                        case "txtKodeFilter": 
                            newValue = txtKodeFilter.getText();
                            if (!newValue.equals(oldValue)) { loadData(); }
                            break;
                            
                        case "txtNamaFilter": 
                            newValue = txtNamaFilter.getText();
                            if (!newValue.equals(oldValue)) { loadData(); }
                            break;
                    };
                break;      
            }
        }
    }
    
    class ActionFocusGained implements FocusListener {
        @Override public void focusGained(FocusEvent e) { 
            Component componen = (Component) e.getSource(); 
            if (componen instanceof JTextField) { oldValue = ((JTextField) componen).getText();
            }else if (componen instanceof JComboBox) { oldValue = ((JComboBox) componen).getSelectedIndex();
            }else if (componen instanceof JCheckBox) { oldValue = ((JCheckBox) componen).isSelected();
            }else if (componen instanceof JTextArea) { oldValue = ((JTextArea) componen).getText(); }
        }
        
        @Override public void focusLost(FocusEvent e) {
            Component componen = (Component) e.getSource(); 
            if (componen instanceof JTextField) { newValue = ((JTextField) componen).getText();
            }else if (componen instanceof JComboBox) { newValue = ((JComboBox) componen).getSelectedIndex();
            }else if (componen instanceof JCheckBox) { newValue = ((JCheckBox) componen).isSelected();
            }else if (componen instanceof JTextArea) { oldValue = ((JTextArea) componen).getText(); }
        }
    }
    
    class ComboboxListener implements ItemListener {
        @Override
        public void itemStateChanged(ItemEvent e) {
            if(e.getStateChange()==ItemEvent.SELECTED) {
                loadData();
            }
        }
    }
    
    private void setTableLookStyle() {
        
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnEdit;
    private javax.swing.JButton btnLoad;
    private javax.swing.JButton btnPrint;
    private javax.swing.JComboBox cmbDays;
    private javax.swing.JTable grid;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPane2;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JTextField txtKodeFilter;
    private javax.swing.JTextField txtNamaFilter;
    // End of variables declaration//GEN-END:variables
}
